package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Collection;
import java.util.Collections;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int data=0;
        String msg="未知错误";
        //1.从前端获取参数
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        if(!StrUtil.isBlank(username) && !StrUtil.isBlank(password)){
            //2.查询数据库
            Connection connection=DBUtils.getConnection();
            String sql=" select * from userinfo where username=? and password=?";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1,username);
            statement.setString(2, SecureUtil.md5(password));
            ResultSet resultSet =statement.executeQuery();
            if(resultSet.next()){
                UserInfo userInfo=new UserInfo();
                userInfo.setUid(resultSet.getInt("uid"));
                userInfo.setUsername(resultSet.getString("username"));
                userInfo.setPassword(resultSet.getString("password"));
                userInfo.setNickname(resultSet.getString("nickname"));
                userInfo.setImg(resultSet.getString("img"));
                userInfo.setGit(resultSet.getString("git"));
                userInfo.setState(resultSet.getInt("state"));
                //将当前登录的用户保存到session中
                //a.得到session对象
                HttpSession session=req.getSession(true);
                if(session!=null){
                    session.setAttribute(AppVar.SESSION_USERINFO_KEY,userInfo);
                }

                data=1;

            }else {
                msg="用户名或密码错误！";
            }
            DBUtils.close(resultSet,statement,connection);
        }else {
            msg="非法参数";
        }

        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,data,msg)));
    }
}

